{% extends 'admin/base.html' %}

{% block cus_head %}
    <!-- 可搜索下拉：Tom Select -->
    <link href="{{ url_for('static', filename='css/tom-select.css') }}" rel="stylesheet">
    <!-- 日期选择：Flatpickr -->
    <link href="{{ url_for('static', filename='css/flatpickr.min.css') }}" rel="stylesheet">
{% endblock %}

{% block content %}
    <div class="w-full px-6 py-8">
        <div class="mb-6 flex justify-between items-center">
            <h1 class="text-2xl font-semibold">电影管理</h1>
            <div class="flex items-center space-x-4">
                <button onclick="showModal('add')"
                        class="px-4 py-2 bg-primary text-white hover:bg-primary/90 !rounded-button whitespace-nowrap">
                    <i class="fas fa-plus mr-2"></i>添加
                </button>
            </div>
        </div>

        <form method="get" action="{{ url_for('admin.manage_movies') }}" class="mt-4 flex items-center space-x-4" style="margin-bottom: 20px">
            <label>
                <input type="text" name="name" value="{{ request.args.get('name', '') }}"
                       placeholder="请输入电影名称"
                       class="border px-3 py-2 rounded-xl focus:outline-none focus:border-primary w-64">
            </label>
            <label>
                <input type="text" name="director" value="{{ request.args.get('director', '') }}"
                       placeholder="请输入导演名称"
                       class="border px-3 py-2 rounded-xl focus:outline-none focus:border-primary w-64">
            </label>
            <button type="submit"
                    class="px-4 py-2 bg-primary text-white rounded-xl hover:bg-primary/90">
                筛选
            </button>
            <a href="{{ url_for('admin.manage_movies') }}"
               class="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl hover:bg-gray-200">重置</a>
        </form>

        <div class="bg-white !rounded-lg shadow">
            <table class="w-full">
                <thead>
                <tr class="text-left border-b border-gray-200">
                    <th class="px-6 py-4 text-sm font-medium text-gray-500">#</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">海报</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">电影名</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">导演</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">上映国家</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">上映年月</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">主演</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">豆瓣评分</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">浏览数量</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">创建时间</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">更新时间</th>
                    <th class="px-6 py-4 text-sm font-medium text-gray-500 text-center">操作</th>
                </tr>
                </thead>
                <tbody>
                {% for movie_data in pagination.current_items %}
                    <tr class="border-b border-gray-200">
                        <td class="px-6 py-4">{{ loop.index }}</td>
                        <td class="px-6 py-4 text-center">
                            <img class="max-w-[100px]" src="{{ url_for('static', filename=movie_data.image_link) }}"
                                 alt="电影海报">
                        </td>
                        <td class="px-6 py-4 text-center truncate max-w-[160px]" title="{{ movie_data.name }}"
                            style="color: #4e7fc7">
                            <a href="{{ url_for('admin.movie_detail', movie_id=movie_data.id) }}">{{ movie_data.name }}</a>
                        </td>
                        <td class="px-6 py-4 text-center">{{ movie_data.director }}</td>
                        <td class="px-6 py-4 text-center">{{ movie_data.country }}</td>
                        <td class="px-6 py-4 text-center">{{ movie_data.years }}</td>
                        <td class="px-6 py-4 text-center truncate max-w-[160px]"
                            title="{{ movie_data.leader }}">{{ movie_data.leader }}</td>
                        <td class="px-6 py-4 text-center">{{ movie_data.rate }}</td>
                        <td class="px-6 py-4 text-center">{{ movie_data.views }}</td>
                        <td class="px-6 py-4 text-center">{{ movie_data.created_at }}</td>
                        <td class="px-6 py-4 text-center">{{ movie_data.updated_at }}</td>
                        <td class="px-6 py-4 text-center">
                            <button onclick="delete_movie('{{ movie_data.id }}')"
                                    class="p-2 text-red-500 hover:bg-red-50 !rounded-button">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
            {% with endpoint='admin.manage_movies', url_params={} %}
                {% include 'admin/components/page.html' with context %}
            {% endwith %}
        </div>
    </div>

    <!-- 模态框 -->
    <div id="movieModal" class="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center hidden">
        <div class="bg-white rounded-2xl shadow-lg w-[1000px] p-6 relative">
            <button onclick="hideModal()" class="absolute top-4 right-4 text-gray-500 hover:text-gray-700">
                <i class="fas fa-times text-xl"></i>
            </button>
            <h3 id="modalTitle" class="text-2xl font-semibold mb-6">添加电影</h3>

            <form id="movieForm" method="post" action="{{ url_for('admin.add_movie') }}" enctype="multipart/form-data"
                  class="space-y-4">
                <div>
                    <label for="name" class="block mb-1 font-medium">电影名</label>
                    <input id="name" name="name" type="text" required
                           class="w-full border px-3 py-2 rounded-xl focus:border-primary focus:outline-none">
                </div>

                <div>
                    <label for="director" class="block mb-1 font-medium">导演</label>
                    <input id="director" name="director" type="text" required
                           class="w-full border px-3 py-2 rounded-xl focus:border-primary focus:outline-none">
                </div>

                <div>
                    <label for="country" class="block mb-1 font-medium">上映国家</label>
                    <select id="country" name="country" class="w-full" required>
                        {% for c in countries %}
                            <option value="{{ c.name_zh }}">{{ c.name_zh }}</option>
                        {% endfor %}
                    </select>
                </div>

                <div>
                    <label for="release_date" class="block mb-1 font-medium">上映时间</label>
                    <input id="release_date" name="years" type="text" required
                           class="w-full border px-3 py-2 rounded-xl focus:border-primary focus:outline-none"
                           placeholder="YYYY-MM-DD">
                </div>

                <div>
                    <label for="leader" class="block mb-1 font-medium">主演</label>
                    <input id="leader" name="leader" type="text" required
                           class="w-full border px-3 py-2 rounded-xl focus:border-primary focus:outline-none"
                           placeholder="多位主演请用“/”分隔">
                </div>

                <div>
                    <label for="rate" class="block mb-1 font-medium">电影评分</label>
                    <input id="rate" name="rate" type="number" step="0.01" min="1" max="10" required
                           class="w-full border px-3 py-2 rounded-xl focus:border-primary focus:outline-none"
                           placeholder="请输入两位小数">
                </div>

                <div>
                    <label for="intro" class="block mb-1 font-medium">电影简介</label>
                    <textarea id="intro" name="intro" rows="4"
                              class="w-full border px-3 py-2 rounded-xl focus:border-primary focus:outline-none"></textarea>
                </div>

                <div>
                    <label for="image" class="block mb-1 font-medium">电影海报</label>
                    <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center" id="dropZone">
                        <div class="mb-4">
                            <i class="fas fa-cloud-upload-alt text-4xl text-gray-400"></i>
                        </div>
                        <p class="text-gray-600 mb-2">拖拽图片到此处或点击上传</p>
                        <p class="text-gray-400 text-sm">支持 jpg、png、jpeg 格式，单个文件不超过 5MB</p>

                        <input name="image" type="file" class="hidden" id="fileInput" accept="image/*" required>
                        <div id="previewContainer" class="mt-4">
                            <img id="imagePreview" src="" alt="预览图"
                                 class="max-w-[200px] mx-auto hidden rounded-lg shadow"/>
                        </div>
                    </div>
                </div>

                <!-- 按钮 -->
                <div class="flex justify-end space-x-4 pt-4">
                    <button type="button" onclick="hideModal()"
                            class="px-4 py-2 bg-gray-100 rounded-xl hover:bg-gray-200">取消
                    </button>
                    <button type="submit"
                            class="px-4 py-2 bg-primary text-white rounded-xl hover:bg-primary/90">保存
                    </button>
                </div>
            </form>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    {{ super() }}
    <script>
        /**
         * 保存当前页, 保证详情页返回时可回到该页
         */
        const page_num = document.getElementById('page_num').innerText;
        sessionStorage.setItem('moviePage', page_num);

        function showModal(type) {
            const modalTitle = document.getElementById('modalTitle');
            modalTitle.textContent = type === 'add' ? '添加电影' : '编辑电影';

            document.getElementById('movieModal').classList.remove('hidden');
        }

        function hideModal() {
            const user_form = document.getElementById('movieForm');
            user_form.onreset;

            const previewImg = document.getElementById('imagePreview');
            const fileInput = document.getElementById('fileInput');
            previewImg.src = '';
            previewImg.classList.add('hidden');
            fileInput.value = '';

            document.getElementById('movieModal').classList.add('hidden');
        }

        function delete_movie(movie_id) {
            // 显示确认弹窗
            showConfirm('确认删除该电影?').then(confirmed => {
                if (confirmed) {
                    // 用户点击确认后执行删除操作
                    fetch(`/admin/delete_movie/${movie_id}`)
                        .then(() => {
                            window.location.href = `/admin/manage_movies/${page_num}`
                        })
                }
            });
        }
    </script>
    <!-- Tom Select -->
    <script src="{{ url_for('static', filename='js/tom-select.complete.min.js') }}"></script>
    <!-- Flatpickr -->
    <script src="{{ url_for('static', filename='js/flatpickr.js') }}"></script>
    <script src="{{ url_for('static', filename='js/zh.js') }}"></script>
    <script>
        // 初始化可搜索下拉
        new TomSelect('#country', {
            maxItems: 1,
            valueField: 'value',
            labelField: 'text',
            searchField: 'text',
            placeholder: '请选择国家...',
        });

        // 初始化日期选择
        flatpickr("#release_date", {
            dateFormat: "Y-m-d",
            locale: "zh",
            allowInput: true,
        });
    </script>
    <script>
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const previewImg = document.getElementById('imagePreview');

        // 点击上传区域时，触发文件选择
        dropZone.addEventListener('click', () => {
            fileInput.click();
        });

        // 拖拽进入高亮
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('bg-gray-100');
        });

        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('bg-gray-100');
        });

        // 拖拽放置文件
        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('bg-gray-100');
            const file = e.dataTransfer.files[0];
            if (file && file.type.startsWith('image/')) {
                fileInput.files = e.dataTransfer.files; // 使文件绑定到 input
                showPreview(file);
            }
        });

        // 监听文件选择变化
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file && file.type.startsWith('image/')) {
                showPreview(file);
            }
        });

        // 显示图片预览
        function showPreview(file) {
            const reader = new FileReader();
            reader.onload = function (e) {
                previewImg.src = e.target.result;
                previewImg.classList.remove('hidden');
            };
            reader.readAsDataURL(file);
        }
    </script>
{% endblock %}